package com.pavlinic.mylisp.specialForms;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import com.pavlinic.mylisp.Expression;
import com.pavlinic.mylisp.ListExpression;
import com.pavlinic.mylisp.SymbolExpression;
import com.pavlinic.mylisp.ValueExpression;

public class New {
  public static Expression evaluateNew(ListExpression listExpression) {
    final String className = ((SymbolExpression) listExpression.get(1)).getValue();
    try {
      final Class<?> clazz = Class.forName(className);
      final Constructor<?> constructor = clazz.getConstructor();
      return new ValueExpression(constructor.newInstance());
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    } catch (SecurityException e) {
      throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
      throw new RuntimeException(e);
    } catch (InstantiationException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
      throw new RuntimeException(e);
    }
  }
}
